package com.example.room.repository;

import android.content.Context;
import android.os.AsyncTask;

import com.example.room.dao.MasterDao;
import com.example.room.database.MyDatabase;
import com.example.room.entity.Master;
import com.example.wjy.room.NativeDatabase;

import java.util.List;

import androidx.lifecycle.LiveData;

/**
 * author: WangJunYan
 * package: com.example.wjy.room
 * date: 2020/6/19
 * time: 16:40
 * 通过此类访问对应的Dao，在子线程中访问数据库
 * 目前的方法只是测试是否可以加载
 */
public class MasterRepository {
    /**
     * Data list from Dao.
     */
    private LiveData<List<Master>> masters;


    private MasterDao masterDao;

    public MasterRepository(Context context) {
        //获取数据库实例，数据库采用单例模式
        MyDatabase database = MyDatabase.getInstance(context.getApplicationContext());
        masterDao = database.getMasterDao();
        masters = masterDao.getAllMaster();
    }

    /**
     * Gets all data from Master table from database.
     * @return The list of masters
     */
    public LiveData<List<Master>> getMasters() {
        return masters;
    }

    public void insertMaster(Master... masters){
        new InsertMasterAsyncTask(masterDao).execute(masters);
    }

     //内部类，用于在子线程中访问数据库，如果有多个操作的话，每一个操作都要对应一个AsyncTask
    static class InsertMasterAsyncTask extends AsyncTask<Master,Void,Void> {
        private MasterDao masterDao;

        public InsertMasterAsyncTask(MasterDao masterDao) {
            this.masterDao = masterDao;
        }

        @Override
        protected Void doInBackground(Master... masters) {
            masterDao.insertMaster(masters);
            return null;
        }
    }

    public void deleteAllMaster() {
        new DeleteAllMasterAsyncTask(masterDao).execute();
    }

    static  class DeleteAllMasterAsyncTask extends AsyncTask<Void,Void,Void> {

        MasterDao masterDao;


        public DeleteAllMasterAsyncTask(MasterDao masterDao) {
            this.masterDao = masterDao;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            masterDao.deleteAllMaster();
            return null;
        }
    }

}
